package com.enjoy.concurrent.ch3;

import sun.misc.Unsafe;

import java.lang.reflect.Field;

public class UnsafeFactory {
    public static Unsafe getUnsafe() throws IllegalAccessException, ClassNotFoundException, NoSuchFieldException {
        Class<?> unsafeClass = Class.forName("sun.misc.Unsafe");
        Field field = unsafeClass.getDeclaredField("theUnsafe");
        field.setAccessible(true);
        return (Unsafe) field.get(null);
    }

    public static long getFieldOffset(Unsafe unsafe, Class<?> entity, String field) throws NoSuchFieldException {
        Field entityField = entity.getField(field);
        return unsafe.objectFieldOffset(entityField);
    }
}
